// pages/center/join.js
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
var app = getApp();
var status = -1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    joinStatus: -1,
    login_code: "",
    login_encryptedData: "",
    login_iv: "",
    shop_id: "",
    shop_user_id: "",
    isHiddenPopView: true,
    mobile: "",
    code: "",
    codeValue: "",
    mobileValue: "",
    enableSend: true,
    HEIGHT: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '加入领班',
    })
    this.shop_id = options.shop_id;
    this.shop_user_id = options.shop_user_id;
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          HEIGHT: res.windowWidth,
        });
      }

    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      codeValue: "",
      mobileValue: "",
      enableSend: true
    })
    this.authorization();
  },

  foremanLogin: function () {
    console.log("login-code", this.login_code);
    if (!this.login_code) {
      util.showError('需要授权后才能登录');
      this.authorization();
      return;
    }
    var that = this;
    var params = new Object()
    params.code = this.login_code;
    params.encryptedData = this.login_encryptedData;
    params.iv = this.login_iv;
    api.POST({
      params: params,
      url: app.globalData.foreman_login_url,
      success: function (res) {
        console.log("loginres", res);
        if (res.data.code) {

          if (res.data.code == '5802') {
            util.showError("密码错误");
            return;
          }
          if (res.data.code == '2400') {
            util.showError('账号不存在');
            return;
          }
          if (res.data.code == '2499') {
            util.hiddenLoading();
            wx.showModal({
              title: '提示',
              content: '请前往已绑定的微信登录;如需解绑或其他问题请联系客服',
              confirmText: '好',
              cancelText: '联系客服',
              success: function (suress) {
                if (!suress.confirm) {
                  wx.makePhoneCall({
                    phoneNumber: '4000788519', //此号码并非真实电话号码，仅用于测试
                    success: function () {
                      console.log("拨打电话成功！")
                    },
                    fail: function () {
                      console.log("拨打电话失败！")
                    }
                  })
                }
              }
            })
          }

        } else {

          app.globalData.loginState = 1;
          wx.setStorageSync("isLogin", "1");
          app.globalData.accountInfo = res.data.data.result;
          that.joinForeman();
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络。");

      }
    })
  },

  joinForeman: function () {

    var params = new Object()
    params.shop_user_id = this.shop_user_id;
    params.shop_id = this.shop_id;
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.foreman_joinForeman_url,
      success: function (res) {
        console.log("joinForman", res);
        status = res.data.data.status;
        that.setData({
          shopName: res.data.data.shop_name,
          avatar: res.data.data.avatar,
          joinStatus: res.data.data.status
        })
      },
      fail: function (fail) {

      }
    })
  },



  //点击申请加入
  joinMethod: function () {
    if (status == 6) {
      util.showError("商家不能成为领班");
      return;
    } else if (status == 5) {
      util.showError("一家门店只能加入一名领班，当前您不能再加入了");
      return;
    } else if (status == 4) {
      util.showError("您已是一家门店的领班，不能再加入了");
      return;
    }
    this.setData({
      isHiddenPopView: false
    })
  },
  noClick: function () {

  },
  // 授权
  authorization: function () {
    var that = this
    wx.login({
      success: function (res_login) {
        wx.getUserInfo({
          withCredentials: true,
          success: function (res_user) {
            that.login_code = res_login.code;
            that.login_encryptedData = res_user.encryptedData;
            that.login_iv = res_user.iv;
            that.foremanLogin();
          }, fail: function (fail_user) {
            wx.showModal({
              title: '警告',
              content: '若不授权登录，则无法登录进行使用',
              confirmText: '授权',
              cancelText: '不授权',
              success: function (suress) {
                if (suress.confirm) {
                  that.reAuthorization();
                }
              }
            })

          }
        })
      }, fail: function (fail_login) {
        console.log("fail");
      }
    })
  },
  // 重新授权
  reAuthorization: function () {
    var that = this
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"]) {
          that.authorization();
        }
      }
    })
  },

  //关闭弹窗
  closeClick: function () {
    this.setData({
      isHiddenPopView: true,
      codeValue: "",
      mobileValue: "",
      enableSend: true,
    })
  },

  // 输入框
  bindPhoneInput: function (e) {
    this.mobile = e.detail.value;
    console.log("codeValue", e.currentTarget.dataset.mobileValue)
  },
  bindCodeInput: function (e) {
    this.code = e.detail.value
  },
  // 获取验证码
  getCodeMethod: function () {

    var isphone = util.validateMobile(this.mobile);
    if (!isphone) {
      util.showError('请输入正确的手机号')
      return;
    }
    var total_micro_second = 60 * 1000;
    //验证码倒计时
    this.count_down(this, total_micro_second);

    var params = new Object()
    params.mobile = this.mobile;
    params.type = "8";
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.captcha_geturl,
      success: function (res) {
        console.log("submit", res.data);
        if (res.data.status == 0) {
          util.showError(res.data.message);
          return;
        }
        that.code = res.data.code;
        util.showStatus("验证码发送成功");
      },
      fail: function (fail) {

      }
    })
  },

  count_down: function (that, total_micro_second) {
    if (total_micro_second <= 0) {
      that.setData({
        VerifyCode: "重新发送",
        enableSend: true,
      });
      // timeout则跳出递归
      return;
    }
    // 渲染倒计时时钟

    that.setData({
      enableSend: false,
      VerifyCode: that.date_format(total_micro_second) + " 秒"
    });
    setTimeout(function () {
      // 放在最后--
      total_micro_second -= 10;
      that.count_down(that, total_micro_second);
    }, 10)
  },
  // 时间格式化输出，如03:25:19 86。每10ms都会调用一次
  date_format: function (micro_second) {
    // 秒数
    var second = Math.floor(micro_second / 1000);
    // 小时位
    var hr = Math.floor(second / 3600);
    // 分钟位
    var min = this.fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
    // 秒位
    var sec = this.fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
    // 毫秒位，保留2位
    var micro_sec = this.fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
    return sec;
  },
  // 位数不足补零
  fill_zero_prefix: function (num) {
    return num < 10 ? "0" + num : num
  },

  // 确认提交
  submitMethod: function () {

    var isphone = util.validateMobile(this.mobile);
    if (!isphone) {
      util.showError('请输入正确的手机号')
      return;
    }
    if (this.code.length < 4) {
      util.showError('请输入验证码')
      return;
    }

    var params = new Object()
    params.shop_user_id = this.shop_user_id;
    params.shop_id = this.shop_id;
    params.mobile = this.mobile;
    params.captcha = this.code;

    var that = this;
    api.POST({
      params: params,
      url: app.globalData.foreman_joinSubmit_url,
      success: function (res) {
        console.log("params", params, "submitres", res);
        if (res.data.status == 0) {
          util.showError(res.data.message);
          return;
        }

        wx.showToast({
          title: "提交成功",

          duration: 3000
        })

        that.setData({
          joinStatus: 1,
          isHiddenPopView: true
        })
      },
      fail: function (fail) {

      }
    })
  },
})